<?php
require_once('inc/config.inc');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
	die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
	die("Unable to select database");
}
mysql_query ('SET NAMES utf8');
mysql_query('SET CHARACTER SET utf8');
$path = "../uploads/";
if($_POST['type']=="File"){
$valid_formats = array("docx", "doc", "pdf", "ppt","pptx");
//if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
//{
$name = $_FILES['file']['name'];
$size = $_FILES['file']['size'];
$r=10;
if(strlen($name))
{
	$r =1;
	list($txt, $ext) = explode(".", $name);
	$ext1 = pathinfo($name, PATHINFO_EXTENSION);
	if(in_array($ext1,$valid_formats))
	{
		$r =2;
		if($size<(100*1024*1024))
		{
			$r =3;
				
			$actual_file_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext1;
			$tmp = $_FILES['file']['tmp_name'];

			$r =4;
			$insert=mysql_query("INSERT INTO course_materials (name,description,date_added,course_id,type) values ('".$_POST['mname']."','".$_POST['desc']."',NOW(),'".$_POST['course_id']."','File')");
			if($insert){
				$select = mysql_query("SELECT material_id FROM course_materials where name = '".$_POST['mname']."'");
				$row = mysql_fetch_array($select);
				$insert_file = mysql_query("INSERT INTO material_file(material_id,file_name) values (".$row[0].",'".$actual_file_name."')");
				if($insert_file){
					$done = move_uploaded_file($tmp, $path.$actual_file_name);
					header("Location: ../courses.php?addmaterial=success");
				}
				else{
					header("Location: ../courses.php?addmaterial=fail");
				}
			}	
				
				
			else
			{echo "failed";$r=77;}
		}
		else
		{echo "file file size max 1 MB";$r=88;}
	}
	else
	{echo "Invalid file format..";$r=99;}
}
}
else{
	$insert=mysql_query("INSERT INTO course_materials (name,description,date_added,course_id,type) values ('".$_POST['mname']."','".$_POST['desc']."',NOW(),'".$_POST['course_id']."','Link')");
	if($insert){
		$select = mysql_query("SELECT material_id FROM course_materials where name = '".$_POST['mname']."'");
		$row = mysql_fetch_array($select);
		$insert_file = mysql_query("INSERT INTO material_link(material_id,url) values (".$row[0].",'".$_POST['url']."')");
		if($insert_file){
			header("Location: ../courses.php?addmaterial=success");
		}
		else{
			header("Location: ../courses.php?addmaterial=fail");
		}
	}
}


?>